import React, { useEffect, useState } from 'react'
import './WrjAuthentication.less'
import { Alert } from 'antd';
import { Button, Flex  } from 'antd';
import Front from '../front/WrjFront';
import Back from '../back/WrjBack'
import { useSelector } from 'react-redux';
import { StoreState } from '../../../store/store';
import request from '../../../utils/axios';


const Authentication:React.FC=()=>{
    const [message,setMessage]=useState("根据《小默外卖用户协议》请先完成实名认证，才可开展配送站相关业务！")
    const [name,setName]=useState('')
    const [idNumber,setIdNumber]=useState('')
    const frontImg=useSelector((store:StoreState)=>{return store?.counter?.frontImg})
    const backImg=useSelector((store:StoreState)=>{return store?.counter?.backImg})
    const [idMsg,setIdMsg]=useState('')
    const [idName,setIdName]=useState('')
    const [idCard,setIdCard]=useState("")

    //获取身份证号信息
    function parseAndExtractInfo(jsonString: string): { idname: string; idnumber: string } {
        let data: any;
        try {
          data = JSON.parse(jsonString);
        } catch (error) {
          throw new Error('Invalid JSON format');
        }
      
        const idname = data.words_result.姓名.words;
        const idnumber = data.words_result['公民身份号码'].words;
      
        if (!idname || !idnumber) {
          throw new Error('Missing required fields in JSON data');
        }
      
        return { idname, idnumber };
    }

    //验证身份证号格式
    function validateIdCard(idCard: string): boolean {
        const idCardRegex = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
        return idCardRegex.test(idCard);
    }

    const getIdNumber=(e:React.ChangeEvent<HTMLInputElement>)=>{
        if(validateIdCard(e.target.value)){
            setIdNumber(e.target.value) 
            setIdMsg('')           
        }else{
            setIdMsg('身份证号格式错误')
        }
        if(e.target.value==''){
            setIdMsg('')
        }
    }

    const certification=async()=>{
        request.get('rest/ocr', { frontImg:frontImg})
        .then(error => {
            console.log('GET error:', error);
        })
        .catch(response => {
            const { idname, idnumber } = parseAndExtractInfo(response.data.peopleList);
            setIdName(idname)
            setIdCard(idnumber)
            if(idNumber!=idnumber && idName!=idname){
                alert('姓名或身份证号不符')
            }else{
                request.post('addPeople', { name:name,idNumber:idNumber,frontImg:frontImg,backImg:backImg })
                .then(error => {
                    console.log('POST error:', error);
                })
                .catch(response => {
                    if(response.data.code==200){
                        setName('')
                        setIdNumber('')
                        alert(response.data.msg)
                    }
                });
            }
        });
    }

    useEffect(()=>{

    },[backImg,frontImg])

    return (
        <div>
            <Alert style={{color:'#FF9900',width:'550px'}} message={message} type="warning" showIcon />
            <br />
            <div className='wrj-authentication-realname'>
                <p>
                    <span>真实姓名：</span>
                    <input type="text" placeholder='请输入站长的真实姓名' style={{paddingLeft:'5px'}} onChange={(e)=>{setName(e.target.value)}}/>
                </p>
                <p>
                    <span>证件类型：</span>
                    <span>居民身份证</span>
                </p>
                <p>
                    <span>证件号：&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <div style={{display:'flex',flexDirection:'column'}}>
                        <input type="text" style={{paddingLeft:'5px'}} placeholder='请输入站长的身份证号' onChange={(e)=>{getIdNumber(e)}}/>
                        <span style={{color:'red',marginTop:'5px',marginLeft:'50px'}}>{idMsg}</span>
                    </div>
                </p>
                <p>
                    <span>证件正面图</span>
                    <Front></Front>
                    <span className='wrj-alert'>支持JPG JPEG PNG格式，大小不超过2M</span>
                </p>
                <p>
                    <span>证件背面图</span>
                    <Back></Back>
                    <span className='wrj-alert'>支持JPG JPEG PNG格式，大小不超过2M</span>
                </p>
            </div>
            <Button type="primary" shape="round" style={{marginLeft:'120px'}} onClick={certification}>提交认证</Button>
        </div>
    )
}

export default Authentication